/* ---------------------------------------------------------------------------------------------
 *
 *            Capital Alliance Software Confidential Proprietary 
 *            (c) Copyright CAS 201{x}, All Rights Reserved
 *                          www.pekall.com
 *
 * ----------------------------------------------------------------------------------------------
 */

package com.android.music.database;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

public class MyProvider extends ContentProvider {
    SQLiteOpenHelper sd;

    private static final UriMatcher sMatcher;
    static {
        sMatcher = new UriMatcher(UriMatcher.NO_MATCH);
        sMatcher.addURI(SQLHelper.AUTHORITY, "t_music_history", SQLHelper.MUSIC_HISTORY_INDEX);
        sMatcher.addURI(SQLHelper.AUTHORITY, "t_music_history/#", SQLHelper.MUSIC_HISTORY_ID_INDEX);
        sMatcher.addURI(SQLHelper.AUTHORITY, "t_my_play_list", SQLHelper.MUSIC_MY_PLAY_LIST_INDEX);
        sMatcher.addURI(SQLHelper.AUTHORITY, "t_my_play_list/#",
                SQLHelper.MUSIC_MY_PLAY_LIST_ID_INDEX);

        sMatcher.addURI(SQLHelper.AUTHORITY, "my_play_list_music_map",
                SQLHelper.MUSIC_MY_PLAY_LIST_MUSIC_MAP_INDEX);
        sMatcher.addURI(SQLHelper.AUTHORITY, "my_play_list_music_map/#",
                SQLHelper.MUSIC_MY_PLAY_LIST_MUSIC_MAP_ID_INDEX);
    }

    private int tableIndex;

    public boolean onCreate() {
        sd = new SQLHelper(this.getContext());
        return true;
    }

    private int isDir;

    private void matchURI(Uri uri) {
        switch (sMatcher.match(uri)) {
            case SQLHelper.MUSIC_HISTORY_INDEX:
                tableIndex = 0;
                isDir = 1;
                break;
            case SQLHelper.MUSIC_MY_PLAY_LIST_INDEX:
                tableIndex = 1;
                isDir = 1;
                break;
            case SQLHelper.MUSIC_MY_PLAY_LIST_MUSIC_MAP_INDEX:
                tableIndex = 2;
                isDir = 1;
                break;
            case SQLHelper.MUSIC_HISTORY_ID_INDEX:
                tableIndex = 0;
                isDir = 2;
                break;
            case SQLHelper.MUSIC_MY_PLAY_LIST_ID_INDEX:
                tableIndex = 1;
                isDir = 2;
                break;
            case SQLHelper.MUSIC_MY_PLAY_LIST_MUSIC_MAP_ID_INDEX:
                tableIndex = 2;
                isDir = 2;
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    @Override
    public String getType(Uri uri) {
        switch (sMatcher.match(uri)) {
            case SQLHelper.MUSIC_HISTORY_INDEX:
            case SQLHelper.MUSIC_MY_PLAY_LIST_INDEX:
            case SQLHelper.MUSIC_MY_PLAY_LIST_MUSIC_MAP_INDEX:
                return SQLHelper.CONTENT_TYPE;
            case SQLHelper.MUSIC_HISTORY_ID_INDEX:
            case SQLHelper.MUSIC_MY_PLAY_LIST_ID_INDEX:
            case SQLHelper.MUSIC_MY_PLAY_LIST_MUSIC_MAP_ID_INDEX:
                return SQLHelper.CONTENT_ITEM_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        matchURI(uri);
        SQLiteDatabase sdb = sd.getWritableDatabase();
        long rowId;
        if (1 != isDir) {
            throw new IllegalArgumentException("Unknow URI " + uri);
        }
        rowId = sdb.insert(SQLHelper.tableName[tableIndex], "_id", values);
        if (rowId > 0) {
            Uri noteUri = ContentUris.withAppendedId(Uri.parse("content://" + SQLHelper.AUTHORITY
                    + "/" + SQLHelper.tableName[tableIndex]), rowId);
            this.getContext().getContentResolver().notifyChange(noteUri, null);
            return noteUri;
        }

        throw new SQLException("Failed to insert row into " + uri);
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        matchURI(uri);
        SQLiteDatabase sdb = sd.getWritableDatabase();
        int count;
        if (isDir == 1)
            count = sdb.delete(SQLHelper.tableName[tableIndex], selection, selectionArgs);

        else if (isDir == 2) {
            String id = uri.getPathSegments().get(1);
            count = sdb.delete(SQLHelper.tableName[tableIndex], "_id" + "=" + id
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : ""),
                    selectionArgs);
        } else
            throw new IllegalArgumentException("Unknown URI " + uri);
        this.getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
            String sortOrder) {
        matchURI(uri);
        SQLiteDatabase sdb = sd.getReadableDatabase();
        Cursor c;
        try {
            if (isDir == 1)
                c = sdb.query(SQLHelper.tableName[tableIndex], projection, selection,
                        selectionArgs, null, null, sortOrder);
            else if (isDir == 2) {
                String id = uri.getPathSegments().get(1);
                c = sdb.query(SQLHelper.tableName[tableIndex], projection, "_id" + "=" + id
                        + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : ""),
                        selectionArgs, null, null, sortOrder);
            } else {
                Log.i("sMatcher.match(uri)", String.valueOf(sMatcher.match(uri)));
                throw new IllegalArgumentException("Query with unknown URI: " + uri);
            }
        } catch (UnsupportedOperationException ex) {
            return null;
        }

        c.setNotificationUri(getContext().getContentResolver(), uri);
        // c.close();
        return c;
    }

    // 更新，与删除类方法类似
    @Override
    public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
        matchURI(uri);
        SQLiteDatabase sdb = sd.getWritableDatabase();
        int count;
        if (isDir == 1) {
            count = sdb.update(SQLHelper.tableName[tableIndex], values, selection, selectionArgs);
        } else if (isDir == 2) {
            String id = uri.getPathSegments().get(1);
            count = sdb.update(SQLHelper.tableName[tableIndex], values, "_id" + "=" + id
                    + (!TextUtils.isEmpty(selection) ? " AND (" + selection + ")" : ""),
                    selectionArgs);
        } else {
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        this.getContext().getContentResolver().notifyChange(uri, null);
        return count;
    }
}
